package com.qf.service.impl;

import com.qf.exceptions.MyBaseException;
import com.qf.exceptions.MyErrorCode;
import com.qf.mapper.SysSceneMapper;
import com.qf.pojo.SysScene;
import com.qf.pojo.SysUserInfo;
import com.qf.service.SysSceneService;
import com.qf.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * created by 赵文韬 on 2022/3/22 20:26
 */
@Service
@Transactional
public class SysSceneServiceImpl implements SysSceneService {
    private SysSceneMapper sysSceneMapper;
    @Autowired
    public void setSysSceneMapper(SysSceneMapper sysSceneMapper) {
        this.sysSceneMapper = sysSceneMapper;
    }

   /* @Override
    public SysScene findByIdAndName(Long sceneId, String sceneName) {
        SysScene sysScene = sysSceneMapper.findByUserAndName(sceneId, sceneName);
        return sysScene;
    }*/

    @Override
    public void addSysScene(SysScene sysScene) {
        Assert.notNull(sysScene,()->{
            throw new MyBaseException("参数不能为空", MyErrorCode.DATA_NULL);
        } );
        //判断用户是否登录
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        Assert.notNull(loginUser,()->{
            throw new MyBaseException("请先登录",MyErrorCode.NOT_LOGIN );
        } );
        /*sysSceneMapper.addSysScene(sysScene);*/
        //根据登录用户的uid和场景的名字来查询数据库中此场景是否已存在
        SysScene sysScene1 = sysSceneMapper.findByUserAndName(loginUser.getUId(),sysScene.getSceneName());
        System.err.println(sysScene1);
        Assert.isTrue(sysScene1==null||sysScene1.getStatus()==0,()->{
            throw new MyBaseException("场景已存在",MyErrorCode.DATA_ALLREADY_EXIST );
        } );
        if (sysScene1==null){
            sysScene.setCreateBy(sysScene.getSceneId());
            sysScene.setCreateTime(new Date());
            sysScene.setCreateBy(loginUser.getUId());
            sysSceneMapper.addSysScene(sysScene);
        }else {
            sysSceneMapper.updateSysScene(sysScene.getSceneId(),1L );
        }
    }

    @Override
    public SysScene findById(Long id) {
        SysScene byId = sysSceneMapper.findById(id);

        return byId;
    }
}
